/**
 * @author paim 09/11/2011
 */
package paim.wingchun.testes;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * @author paim 09/11/2011 <br>
 *         StrongReference <br>
 *         - SoftReference <br>
 *         - WeakReference <br>
 *         - PhantomReference <br>
 */
public class References {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args) {

        printInfoMemory();
        System.out.println("-- before creating 1MB object");
        OneMegaByte oneMB = new OneMegaByte();

        //        PhantomReference soft = new PhantomReference(oneMB);
        //        SoftReference soft = new SoftReference(oneMB);
        WeakReference soft = new WeakReference(oneMB);

        System.out.println("-- after creating 1MB object" + soft.get());
        printInfoMemory();
        System.out.println("-- consuming memory");

        int INTERACTIONS = 100;
        List l = new ArrayList(INTERACTIONS);
        oneMB = null;

        for ( int i = 0; i < INTERACTIONS; i++ ) {
            l.add(new OneMegaByte());
            printInfoMemory();

            Object o = soft.get();
            if ( o != null ) {
                System.out.println(">>>>>>>>  oneMB is still alive!!! " + o);
            }
            else {
                System.out.println("<<<<<<<<  oneMB was garbaged !!!");
            }
        }

    }

    static int count;

    static void printInfoMemory() {
        System.out.println("#######   " + (count++));
        System.out.println("### TOTAL MEMORY = " + Runtime.getRuntime().totalMemory());
        System.out.println("### FREE MEMORY = " + Runtime.getRuntime().freeMemory());
    }

}


class OneMegaByte {

    static int instanceCount = 1;

    int id;

    byte[] ONE_MB = new byte[1024 * 512];

    OneMegaByte() {
        id = instanceCount++;
        for ( int i = 0; i < ONE_MB.length; i++ ) {
            ONE_MB[i] = (byte) i;
        }
    }

    @Override
    public String toString() {
        return "One MegaByte\'s Object [" + id + "]";
    }

}
